package com.example.demo.testannotation;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2024-01-25
 * Time: 17:08
 */

/**
 * 定义拦截器
 */
@Component
public class IdempotentInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.先获取到拦截的方法
        Method method = ((HandlerMethod) handler).getMethod();
        // 2.获取拦截方法的指定注解
        Idempotent idempotent = method.getAnnotation(Idempotent.class);
        // 3.执行幂等业务
        if (idempotent != null) {
            System.out.println("请求Id："+idempotent.requstId()+", 幂等超时时间："+idempotent.expireTime()+".");
            // ... 存入 redis
            // ... 从 redis 中取
            return true;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
